import java.util.ArrayList;
import java.util.List;

public class PriorityScheduler {
    //实现优先级调度算法
    public static void prioritySchedule(List<PCB> processes) {
        List<PCB> finishList = new ArrayList<>();
        //currentTime记录当前系统时间
        int currentTime = 0;
        while (!processes.isEmpty()) {
            PCB current = processes.get(0);
            for (PCB p : processes) {
                //找优先级最高的进程，即数值最小的
                if (p.priority < current.priority) {
                    current = p;
                }
            }
            current.state = "运行";
            //在优先权调度算法这种非抢占式调度场景下，一旦选中一个进程，就会让它一次把所有的需要的cpu时间都用完
            current.cpuTime = current.allTime;
            current.remainTime = 0;
            //当前系统时间+该进程总共需要运行的时间
            current.finishTime = currentTime + current.allTime;
            //更新当前系统时间
            currentTime = current.finishTime;
            current.state = "结束";
            finishList.add(current);
            processes.remove(current);
        }
        printProcessInfo(finishList);
        printMetrics(finishList);
    }

    private static void printProcessInfo(List<PCB> processes) {
        //打印进程信息
        System.out.println("进程ID\t优先级\t已用CPU时间\t总需时间\t结束时间\t状态");
        for (PCB p : processes) {
            System.out.println(p.id + "\t\t" + p.priority + "\t\t" + p.cpuTime + "\t\t" + p.allTime + "\t\t" + p.finishTime + "\t\t" + p.state);
        }
    }

    private static void printMetrics(List<PCB> processes) {
        //打印平均周转时间
        double totalTurnaroundTime = 0;
        for (PCB p : processes) {
            double turnaroundTime = p.finishTime;
            totalTurnaroundTime += turnaroundTime;
        }
        double averageTurnaroundTime = totalTurnaroundTime / processes.size();
        System.out.println("平均周转时间: " + averageTurnaroundTime);
    }
}
